//
//  WBoAuthViewController.swift
//  weibo
//
//  Created by  郭航 on 16/6/25.
//  Copyright © 2016年 郭航. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBoAuthViewController: UIViewController {
    
    override func loadView() {
        let webView = UIWebView()
        
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "OAuth登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(WBoAuthViewController.leftItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(WBoAuthViewController.rightItemClick))

        let URL = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKey)&redirect_uri=\(APPRedirect_uri)")
        let URLRes = NSURLRequest(URL: URL!)
        
        let webView = view as! UIWebView
        webView.loadRequest(URLRes)
    }
    
    func leftItemClick() -> Void {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func rightItemClick() -> Void {
        let userName = "15662130607"
        let password = "wb123456"
        
        let jsStr = "document.getElementById('userId').value = '\(userName)', document.getElementById('passwd').value = '\(password)'"
        
        let webView = view as! UIWebView
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }
    
}

extension WBoAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let URLStr = request.URL?.absoluteString
        
        if let u = URLStr where u.hasPrefix(APPRedirect_uri) {
            let query = request.URL?.query
            let code = query?.substringFromIndex("code=".endIndex)
            
            WBNetworktool.shareNetworktool.oAuthGetAccessToken(code!, success: { (response) in
                
                guard let res = response as? [String:AnyObject] else {
                    return
                }
                
                let userInforModel = WBUserInforModel(dic: res)
                
                WBNetworktool.shareNetworktool.oAuthGetUserInfor(userInforModel, success: { (response) in
                    
                    guard let res = response as? [String:AnyObject] else {
                        return
                    }
                    
                    userInforModel.screen_name = res["screen_name"] as? String
                    userInforModel.avatar_large = res["avatar_large"] as? String
                    
                    WBUserInfor.shareWBUserInfor.saveUserInfor(userInforModel)
                    
                    SVProgressHUD.dismiss()
                    
                    self.dismissViewControllerAnimated(false, completion: {
                        NSNotificationCenter.defaultCenter().postNotificationName(NotChangeKeyWindows, object: "login")
                    })
                    
                    }, failure: { (error) in
                        print("error:\(error)")
                })
                
                }, failure: { (error) in
                    print("error:\(error)")
            })
            return false
        }
        
        return true
    }
    
}
